package io.github.veigara.tcp.framework.utils;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufUtil;

/**
 * @author : zhouhx
 * @date : 2025/6/6 17:15
 */
public class BytesUtil {
    /**
     * 字节数组转换为十六进制
     *
     * @param src
     * @return
     */
    public static String bytesToHexString(byte[] src) {
        StringBuffer sb = new StringBuffer("");
        if (src == null || src.length <= 0) {
            return null;
        }
        for (int i = 0; i < src.length; i++) {
            int v = src[i] & 0xFF;
            String hv = Integer.toHexString(v).toUpperCase();
            if (hv.length() < 2) {
                sb.append(0);
            }
            sb.append(hv);
            if (i != src.length - 1) {
                sb.append(" ");
            }
        }
        return sb.toString();
    }

    public static String hexDumpUpperCaseWithSpace(ByteBuf buf) {
        String hex = ByteBufUtil.hexDump(buf);
        StringBuilder upperCaseHex = new StringBuilder();
        for (int i = 0; i < hex.length(); i += 2) {
            if (i > 0) {
                upperCaseHex.append(" ");
            }
            upperCaseHex.append(hex.substring(i, Math.min(i + 2, hex.length())).toUpperCase());
        }
        return upperCaseHex.toString();
    }
}
